const router = require('koa-router')()
const User = require('../dbs/models/users')
const Passport = require('../utils/passport.js')

router.prefix('/api/users')

// 注册
router.post('/signup', async (ctx) => {
  let { userName, userPwd, email } = ctx.request.body

  let user = await User.find({ userName })
  if (user.length) {
    ctx.body = {
      code: -1,
      msg: '该用户，已被注册'
    }
    return
  }
  // 创建新用户
  let nuser = await User.create({
    userName, userPwd, email
  })

  if (nuser) {
    ctx.body = {
      status: 200,
      data: { userName, email },
      msg: '注册成功'
    }
  } else {
    ctx.body = {
      status: 0,
      msg: '注册失败'
    }
  }
})

// 登录
router.post('/signin', async (ctx) => {
  let { userName, userPwd } = ctx.request.body
  let where = {
    userName
  };
  let result = await User.findOne(where)
  if(result!=null){
    if(result.userPwd===userPwd){
      ctx.body = {
        status: 200,
        msg: '登录成功'
      }
    } else {
      ctx.body = {
        status: 0,
        msg: '密码错误'
      }
    }
  }else{
    ctx.body = {
      status: 0,
      msg: '用户不存在'
    }
  }
})

module.exports = router
